//
//  WLTool.m
//  Kangyx
//
//  Created by 王乐乐 on 16/9/14.
//  Copyright © 2016年 Wanglele. All rights reserved.
//

#import "WLTool.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AdSupport/AdSupport.h>
static NSString * const KEY_IN_KEYCHAIN = @"com.ziyijinfu.key";
static NSString * const KEY_ZIYIJINFU_UUID = @"com.ziyijinfu.appuuid";
@interface WLTool ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
/**************图片选择器**************/
@property(nonatomic, copy )BlkToChooseImg blkChooseImg;
@property(nonatomic, copy )void(^blkSaveImgToPhotoAlbum)(BOOL isSuccess);

@property(nonatomic,assign)NSInteger type;

@property(nonatomic,strong)UIImagePickerController * imagePickerView ;
/******************图片选择器*********/

@property (strong, nonatomic) UIWebView *mainWebView;//拨打电话


@end

@implementation WLTool

//拨打电话
+ (void)makeTelephoneCall:(NSString *)telNumber{
    [[self new] wl_callPhone:telNumber];
}

- (void)wl_callPhone:(NSString *)telNumber{
    static const NSInteger telTag = 19009527;
    NSString *str = [NSString stringWithFormat:@"tel:%@",telNumber];
    if (!_mainWebView) {
        _mainWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
        _mainWebView.tag = telTag;
    }
    [self.mainWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//    UIView *tempView = [SharedApplication.keyWindow viewWithTag:telTag];
//    if (tempView) {
//        [tempView removeFromSuperview];
//    }
//    [SharedApplication.keyWindow addSubview:self.mainWebView];

}

/**
 *  跳转到系统设置页面，iOS8之后可用
 */
- (void)gotoSettings{
    if (&UIApplicationOpenSettingsURLString != NULL) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString: UIApplicationOpenSettingsURLString]];
    }
}

/**
 *  生成设备的UUID，iOS6之后可用
 *
 *  @return uuid字符串
 */
+ (NSString *)getUUIDString{
    NSString *strUUID = [[UIDevice currentDevice] identifierForVendor].UUIDString;
    return strUUID;
}

/**
 *  获取当前显示的viewcontroller
 *
 *  @return return 当前显示的vc
 */
+ (UIViewController *)obtainTopViewController{
    return [WLTool obtainTopViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
+ (UIViewController*)obtainTopViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [WLTool obtainTopViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [WLTool obtainTopViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [WLTool obtainTopViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}


#pragma mark -------  控件兵工厂＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝

/**
 *  快捷创建导航按钮
 *  @param  image 正常图片
 *  @param  highImage 高亮图片
 *  @param  target 代理对象
 *  @param  action 函数
 *  @return return UIBarButtonItem
 */
+ (UIBarButtonItem *)wl_itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

/**
 *  快捷创建导航按钮
 *  @param  title 标题
 *  @return return UIBarButtonItem
 */
+ (UIBarButtonItem *)wl_itemWithTitleColor:(UIColor *)titleColor title:(NSString *)title target:(id)target action:(SEL)action{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

/**
 *  生成UITextField (只有默认文字的）
 *
 *  @param height            高度
 *  @param leftViewWidth  左边提示宽度
 *  @param bSecurity      是否是安全输入
 *  @param keyboardType   键盘类型
 *  @param bSecurity       是否安全输入
*  @param  leftText           左边文字
 *  @param placeholder      placeHolder
 *
 *  @return UITextField
 */
+ (UITextField *)wl_getTFWithleftViewWidth:(CGFloat)leftViewWidth keyBoardType:(UIKeyboardType)keyboardType isSecurity:(BOOL)bSecurity leftText:(NSString *)leftText placeholder:(NSString *)placeholder{
    UITextField * TF = [UITextField new];
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake(kPaddingValue, 0, leftViewWidth, kTFHeight)];
    lab.text = leftText;
    lab.textAlignment = NSTextAlignmentCenter;
    TF.secureTextEntry = bSecurity;
    TF.keyboardType = keyboardType;
    TF.placeholder = placeholder;
    TF.backgroundColor = [UIColor whiteColor];
    TF.leftView = lab;
    TF.leftViewMode = UITextFieldViewModeAlways;
    UIButton *clearButton = [TF valueForKey:@"_clearButton"];
    clearButton.tag = 301;//用于解决和隐藏键盘事件冲突
    return TF;
}

#pragma mark__________________图片选择器__________________________

-(void)chooseImageWithType:(NSInteger)isLibrary FromViewController:(UIViewController *)fromVC Result:(BlkToChooseImg)result
{
    
    self.blkChooseImg = result;
    self.type = isLibrary;
    UIImagePickerController * imagePickerView = [[UIImagePickerController alloc]init];
    self.imagePickerView = imagePickerView;
    imagePickerView.delegate = self;
    imagePickerView.allowsEditing = YES;
    imagePickerView.videoQuality = UIImagePickerControllerQualityTypeLow;
    if (isLibrary == 0)
    {
        if (TARGET_IPHONE_SIMULATOR == NO)
        {
            imagePickerView.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
    }else
    {
        imagePickerView.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    [fromVC presentViewController:imagePickerView animated:YES completion:^{
        
    }];
}

//保存图片到相册
-(void)saveImageToPhotosAlbum:(UIImage *)image  Result:(void(^)(BOOL isSuccess))result
{
    self.blkSaveImgToPhotoAlbum = result;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    if (self.blkSaveImgToPhotoAlbum)
    {
        self.blkSaveImgToPhotoAlbum(error == NULL);
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //获取媒体类型
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //判断是静态图像还是视频
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
    {
        //获取到的图片信息
        UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
        if (self.blkChooseImg)
        {
            self.blkChooseImg(image);
        }
    }
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

+ (NSString*)getCurrentTimestamp{
    NSDate *datenow = [NSDate date];
    NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    NSInteger interval = [zone secondsFromGMTForDate:datenow];
    NSDate *localeDate = [datenow dateByAddingTimeInterval:interval];
    NSString *timeSp = [NSString stringWithFormat:@"%f", [localeDate timeIntervalSince1970]];
    return timeSp;
}

+ (NSString*)generateImageName{
    return [WLTool getCurrentTimestamp];
}

+ (BOOL)saveImageWithName:(NSString*)imageName andImage:(UIImage*)image{
    if (imageName && [imageName isKindOfClass:[NSString class]] && imageName.length > 0 && image && [image isKindOfClass:[UIImage class]]) {
        NSData* imageData = UIImageJPEGRepresentation(image,0.5);
        //获取Library/Caches目录
        NSString *imagePath = [WLTool generateImagePathwithName:imageName];
        [imageData writeToFile:imagePath atomically:NO];
        return YES;
    }
    return NO;
}

+ (UIImage*)loadImageWithName:(NSString*)imageName{
    NSString *imagePath = [WLTool generateImagePathwithName:imageName];
    UIImage *reslutImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:imagePath]]];
    return reslutImage;
}

+ (void)deleteImageWithName:(NSString*)imageName{
    NSString *imagePath = [WLTool generateImagePathwithName:imageName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
    }
}

+ (NSString*)generateImagePathwithName:(NSString*)imageName{
    if (imageName && [imageName isKindOfClass:[NSString class]] && imageName.length > 0){
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) lastObject];
        NSString *imagePathTemp = [cachesPath stringByAppendingPathComponent:@"Meixiangshenghuo"];
        NSError *error = nil;
        if (![[NSFileManager defaultManager] fileExistsAtPath:imagePathTemp]){
            [[NSFileManager defaultManager] createDirectoryAtPath:imagePathTemp withIntermediateDirectories:NO attributes:nil error:&error];
        }
        NSString *imagePath = [imagePathTemp stringByAppendingPathComponent:imageName];
        return imagePath;
    }else{
        return @"";
    }
}

+ (void)clearLocalImageCache{
    NSString *cachesPath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) lastObject];
    NSString *imagePathTemp = [cachesPath stringByAppendingPathComponent:@"Meixiangshenghuo"];
    NSError *error = nil;
    for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:imagePathTemp error:&error]) {
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", imagePathTemp, file] error:&error];
    }
}

+ (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)compressImage:(UIImage *)image toTargetsize:(float)size{
    UIImage *img1 = [WLTool compressImage:image toTargetWidth:image.size.width/2];
    NSData *data = UIImageJPEGRepresentation(img1, 0.5);
    if(data.length >= size*1024) {
        [self compressImage:img1 toTargetsize:size];
    }
    return img1;
}

/**
 *  延迟执行
 *
 *  @param delay 延迟时间
 *  @param block 执行内容
 *
 *  @return BOOL 方便于控制叠加操作
 */
+ (BOOL)wl_afterPerformWithDelay:(NSTimeInterval)delay block:(void(^)())block{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            block();
        });
    return YES;
}

/**
 判断是否是iPhone X系列
 */
+ (BOOL)isiPhoneXSeries{
    BOOL iPhoneXSeries = false;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {
        return iPhoneXSeries;
    }
    if (@available(iOS 11.0,*)) {
        UIWindow *keyWindow = UIApplication.sharedApplication.keyWindow;
        if (keyWindow.safeAreaInsets.bottom>0.0) {
            iPhoneXSeries = true;
        }
    }
    return iPhoneXSeries;
}

+ (void)saveNetWorkImageToLocal:(NSString*)imageUrl withImageName:(NSString*)imageName{
    if (imageUrl == nil || imageName == nil) {
        return;
    }
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        //加载图片
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *currentImage = [UIImage imageWithData:imageData];
        //本地沙河目录
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        //得到本地沙河中文件路径
        NSString *imageFilePath = [path stringByAppendingPathComponent:imageName];
        
        //将取得的图片写入本地沙盒中
        BOOL success = [UIImageJPEGRepresentation(currentImage, 0.95) writeToFile:imageFilePath atomically:true];
        if (success) {
            NSLog(@"图片保存成功");
        }else{
            NSLog(@"图片保存失败");
        }
        
    });

}
/**
 从本地存储 加载 首页无网状态时的 网络图片
 */
+ (UIImage*)getNetWorkImageFromLocalWithImageName:(NSString*)imageName{
 
        //本地沙河目录
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        //得到本地沙河中文件路径
        NSString *imageFilePath = [path stringByAppendingPathComponent:imageName];
         if ([[NSFileManager defaultManager] fileExistsAtPath:imageFilePath]){
            UIImage *reslutImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:imageFilePath]]];
             return reslutImage;
         }
         return nil;
}
#pragma mark - 获取IDFA 标识
+ (NSString*)getAppIDFA{
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return adId;
}
#pragma mark - 获取唯一识别号
+ (NSString*)getAppDeviceUdid{
    
    /*为保证唯一性此处把udid保存在系统的 keychain中，防止用户卸载app重新安装后uuid改变导致无法获取系统消息列表*/
    NSMutableDictionary *uuidDict = (NSMutableDictionary *)[self load:KEY_IN_KEYCHAIN];
    NSString *UUID = [uuidDict objectForKey:KEY_ZIYIJINFU_UUID];
    
    if (UUID == nil || UUID.length == 0) {
        /*没有获取到，获取一次UUID保存到keychain中*/
        NSString * currentUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        UUID = currentUUID;
        NSMutableDictionary *saveDict = [NSMutableDictionary dictionary];
        [saveDict setObject:currentUUID forKey:KEY_ZIYIJINFU_UUID];
        [self save:KEY_IN_KEYCHAIN data:saveDict];
    }
    
    return UUID;
    
}
+ (id)load:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge_transfer id)kSecReturnData];
    [keychainQuery setObject:(__bridge_transfer id)kSecMatchLimitOne forKey:(__bridge_transfer id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge_retained CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    CFRelease((__bridge CFTypeRef)(keychainQuery));
    return ret;
}
#pragma mark --------   keychain中保存信息API ------------------------------------------
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge_transfer id)kSecClassGenericPassword,(__bridge_transfer id)kSecClass,
            service, (__bridge_transfer id)kSecAttrService,
            service, (__bridge_transfer id)kSecAttrAccount,
            (__bridge_transfer id)kSecAttrAccessibleAfterFirstUnlock,(__bridge_transfer id)kSecAttrAccessible,
            nil];
}

+ (void)save:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((__bridge_retained CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge_transfer id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((__bridge_retained CFDictionaryRef)keychainQuery, NULL);
    
    CFRelease((__bridge CFTypeRef)(keychainQuery));
}
@end
